<template>
	<div>
		<el-upload
			:action="$util.baseUrl + uploadUrl" 
			:headers="{token: $store.getters.token}"
			:accept="'.' + format" 
			:show-file-list="false" 
			:before-upload="beforeUpload" 
			:on-progress="onUploading"
			:on-success="onUploaded">
			<el-button icon="el-icon-upload">选择视频</el-button>
		</el-upload>
		
		<!-- 上传进度可视化 -->
		<el-dialog title="视频上传中..." :visible="isUploading" :close-on-click-modal="false" :close-on-press-escape="false"
		 :show-close="false" width="30vw" append-to-body>
			<div class="progress-wrap">
				<el-progress type="circle" :percentage="percentage" :stroke-width="10" :width="200"></el-progress>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		props: {
			videoUrl: String,
			uploadUrl: String
		},
		data() {
			return {
				format: 'mp4',
				percentage: 0,
				isUploading: false
			}
		},
		methods: {
			beforeUpload(file) {
				const format = file.type.split('/')[1];
				if (format != this.format) return this.$util.msg(`视频仅支持${this.format}格式`);
				if (file.size / 1024 / 1024 > 100) return this.$util.msg('视频大小不能超过100MB');

				this.percentage = 0;
				return this.isUploading = true;
			},
			onUploading(e) {
				this.percentage = Number((e.percent / 1.2).toFixed(0));
			},
			onUploaded(res) {
				this.isUploading = false;

				if (res.state == 'ok') {
					this.$emit('update:videoUrl', res.url);
				} else {
					this.$util.msg(res.msg);
				}
			}
		}
	}
</script>

<style>
	.progress-wrap {
		text-align: center;
		padding: 30px 0;
	}
</style>
